<template>
  <div>
    <el-card>
      <div slot="header">文章列表</div>
      <el-row type="flex" justify="start" align="middle">
        <el-col :span="7">
          文章分类
          <el-select v-model="selectparams.cate_id">
            <el-option
              v-for="(item, index) in artCateList"
              :value="item.id"
              :label="item.cate_name"
              :key="index"
            ></el-option>
          </el-select>
        </el-col>

        <el-col :span="7">
          文章状态
          <el-select v-model="selectparams.state">
            <el-option
              v-for="(item, index) in artStates"
              :key="index"
              :value="item"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button size="mini" type="primary" @click="filterArticle"
            >筛选</el-button
          >
          <el-button size="mini" type="info" @click="resetFilter"
            >重置</el-button
          >
        </el-col>
        <el-col :span="2" :offset="5">
          <el-button size="mini" type="primary">发表文章</el-button>
        </el-col>
      </el-row>
      <div class="body">
        <el-table :data="artList" border>
          <el-table-column
            width="300px"
            label="文章列表"
            prop="title"
          ></el-table-column>
          <el-table-column
            width="100px"
            label="分类"
            prop="cate_name"
          ></el-table-column>
          <el-table-column label="发表时间" prop="pub_date"></el-table-column>
          <el-table-column label="状态" prop="state"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="editArticle(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="delArticle(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row>
          <el-pagination
            background
            :page-sizes="pagesizes"
            :page-size="params.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="(num) => (params.pagesize = num)"
            @current-change="(num) => (params.pagenum = num)"
            @prev-click="params.pagenum--"
            @next-click="params.pagenum++"
          >
          </el-pagination>
        </el-row>
      </div>
    </el-card>

    <el-drawer :size="'800px'" title="我是标题" :visible.sync="showDrawer">
      <el-form label-width="80px">
        <el-form-item label="文章标题">
          <el-input v-model="editArticleData.title"></el-input>
        </el-form-item>
        <el-form-item label="文章分类">
          <el-select style="width: 100%" v-model="editArticleData.cate_id">
            <el-option
              v-for="(item, index) in artCateList"
              :value="item.id"
              :label="item.cate_name"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章状态">
          <el-select style="width: 100%" v-model="editArticleData.state">
            <el-option
              v-for="(item, index) in artStates"
              :key="index"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <quill-editor
            v-model.trim="editArticleData.content"
            :options="{ placeholder: '这里可以填写内容' }"
            ref="myQuillEditor"
          >
          </quill-editor>
        </el-form-item>

        <el-form-item label="文章封面">
          <div style="margin-top: 5px">
            <span class="changeCoverText" @click="selectCover">更换封面</span>
            <span>
              <input type="file" class="changeCoverInp" accept="image/*"
            /></span>
          </div>

          <el-row type="flex" align="bottom">
            <el-col>
              <img :src="coverImg" class="drawerimg" alt="" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="space-around">
            <el-col :span="5">
              <el-button type="primary" size="mini" @click="saveArticle"
                >保存</el-button
              >
              <el-button size="mini" @click="showDrawer = false"
                >取消</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import {
  getArtList,
  getArtCate,
  getArtInfo,
  saveArt,
  delArt
} from '@/api/article'
import moment from 'js-moment'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      params: {
        pagenum: 1,
        pagesize: 5,
        cate_id: '',
        state: '已发布'
      },
      artList: [],
      total: 0,
      pagesizes: [2, 3, 4, 5],
      artCateList: [],
      cateValue: '',
      artStates: ['已发布', '草稿'],
      selectparams: {
        cate_id: '',
        state: '已发布'
      },
      showDrawer: false,
      editArticleData: {},
      coverImg: ''
    }
  },
  created () {
    this.infoArticle()

    // 获取文章分类
    getArtCate().then((res) => {
      this.artCateList = res.data
    })
  },
  mounted () {
    document.getElementsByClassName(
      'el-pagination__jump'
    )[0].childNodes[0].nodeValue = '跳至'
  },
  methods: {
    infoArticle () {
      getArtList(this.params).then((res) => {
        res.data.forEach((item) => {
          item.pub_date = moment(item.pub_date).format()
        })
        this.artList = res.data
        this.total = +res.total
      })
    },
    filterArticle () {
      this.params = { ...this.params, ...this.selectparams }
    },
    resetFilter () {
      this.params = {
        pagenum: 1,
        pagesize: 5,
        cate_id: '',
        state: '已发布'
      }
      this.selectparams = {
        cate_id: '',
        state: '已发布'
      }
    },
    async editArticle (article) {
      const loadingInstance = this.$loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      await getArtInfo({ id: article.id }).then((res) => {
        this.coverImg =
          'http://big-event-vue-api-t.itheima.net' + res.data.cover_img

        this.getFileFromUrl(this.coverImg).then((file) => {
          res.data.cover_img = file
        })
        this.showDrawer = true
        this.editArticleData = res.data
      })
      setTimeout(() => {
        loadingInstance.close()
      })
    },
    selectCover () {
      const coverInp = document.querySelector('.changeCoverInp')
      coverInp.click()

      coverInp.addEventListener('change', () => {
        this.editArticleData.cover_img = coverInp.files[0]
        const reader = new FileReader()
        reader.readAsDataURL(coverInp.files[0])
        reader.onload = () => {
          console.log(reader.result)
          // 将base64作为src的属性传递给 imgURL
          this.coverImg = reader.result
        }
      })
    },
    getFileFromUrl (url, fileName = 'cover') {
      return new Promise((resolve, reject) => {
        let blob = null
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url)
        xhr.setRequestHeader('Accept', 'image/png')
        xhr.responseType = 'blob'
        // 加载时处理
        xhr.onload = () => {
          // 获取返回结果
          blob = xhr.response
          const file = new File([blob], fileName, { type: 'image/png' })
          // 返回结果
          resolve(file)
        }
        xhr.onerror = (e) => {
          reject(e)
        }
        // 发送
        xhr.send()
      })
    },
    async saveArticle () {
      const params = new FormData()
      Object.keys(this.editArticleData).forEach((item) => {
        params.append(item, this.editArticleData[item])
      })
      await saveArt(params).then((res) => {
        this.$message.success(res.message)
        this.showDrawer = false
        this.infoArticle()
      })
    },
    delArticle (article) {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await delArt({ id: article.id }).then((res) => {
            this.$message({ type: 'success', message: res.message })
            this.infoArticle()
          })
        })
        .catch(() => {
          this.$message({ type: 'info', message: '已取消删除' })
        })
    }
  },
  watch: {
    params: {
      deep: true,
      handler () {
        this.infoArticle()
      }
    }
  }
}
</script>

<style scoped lang="less">
.el-card {
  .el-row {
    padding: 20px 0;
  }
  .el-row:nth-child(1) {
    padding-top: 0;
  }
}

.el-drawer {
  .drawerimg {
    width: 250px;
    height: 200px;
    object-fit: contain;
  }
  .el-form {
    .el-form-item {
      .changeCoverText {
        display: block;
        width: 88px;
        height: 32px;
        text-align: center;
        line-height: 32px;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 3px;
        border: 1px solid #dcdcdc;
        cursor: pointer;
      }
      .changeCoverInp {
        display: none;
      }
    }
  }
}

:deep(.el-form-item__content) {
  line-height: 24px;
  .quill-editor {
    .ql-container.ql-snow {
      height: 180px;
    }
  }
}
</style>
